package com.LeeCode;

import org.junit.jupiter.api.Test;

/**
 * 两数相加
 **/

public class Code002 {
    public static void main(String[] args) {
        int[] arr1 = {9};
        int[] arr2 = {9};

        ListNode l1 = Utils.arrayToListNode(arr1);
        ListNode l2 = Utils.arrayToListNode(arr2);

        ListNode res = new Code002().addTwoNumbers1(l1, l2);

        Utils.printListNode(res);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int aux = 0;
        ListNode res = new ListNode(0);
        ListNode current = res;

        while (l1 != null & l2 != null) {
            int tmp = aux + l1.val + l2.val;
            current.next = new ListNode(tmp % 10);
            aux = tmp / 10;
            current = current.next;
            l1 = l1.next;
            l2 = l2.next;
        }

        while (l1 != null) {
            int tmp = aux + l1.val;
            current.next = new ListNode(tmp % 10);
            aux = tmp / 10;
            current = current.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            int tmp = aux + l2.val;
            current.next = new ListNode(tmp % 10);
            aux = tmp / 10;
            current = current.next;
            l2 = l2.next;
        }

        if (aux != 0) {
            current.next = new ListNode(aux);
        }
        return res.next;
    }

    // 尽量少开辟内存
    public ListNode addTwoNumbers1(ListNode l1, ListNode l2) {
        ListNode ans = l1;

        int carry = 0;
        while (l1 != null || l2 != null) {
            int v1 = l1 != null ? l1.val : 0;
            int v2 = l2 != null ? l2.val : 0;
            int tmp = v1 + v2 + carry;

            carry = tmp > 9 ? 1 : 0;
            //开辟额外内存
            // 1.有进位但l1没了
            if (carry > 0 && l1.next == null)
                l1.next = new ListNode(0);
            // 2.l1没了且没有进位 但是l2还有 这里要用短路与符号，不然最后一个判断式会报空指针异常
            if (l1.next == null && l2 != null && l2.next != null)
                l1.next = new ListNode(0);
            l1.val = tmp % 10;
            l1 = l1.next;
            if (l2 != null)
                l2 = l2.next;
        }
        return ans;
    }


    @Test
    public void test() {
        System.out.println(12 % 10);
        System.out.println(12 / 10);
    }
}


